<script lang="ts" setup>
import { ref, watch } from 'vue';
import { message } from 'ant-design-vue';
import { getAllInformationForSubchapterMoveApi, handleSubchapterMove } from '@/api/Teacher/subchapterApi';

// Props 传递
const props = defineProps<{
  isVisible: boolean;
  onClose: () => void;
  courseFileId: string;
  courseId: string;
  resourceId: string;
  sectionId: string;
  fetchCourseData: (courseFileId: string | null, load: boolean, searchValue: string) => Promise<void>;
}>();

// 状态定义
const levels = ref<any[]>([]); // 保存每一层的章节数据
const selections = ref<string[]>([]); // 保存每层级的选择

// 获取章节数据
const fetchChildren = async (parentId: string | null = null, level = 0) => {
  try {
    const response = await getAllInformationForSubchapterMoveApi(parentId || props.courseFileId);
    const courseData = response.data;

    // 过滤掉非文件夹以及当前 sectionId 的项
    const options = courseData
      .filter((chapter: any) => chapter.isFolder && chapter.resourceId !== props.sectionId) // 排除自己
      .map((chapter: any) => ({
        label: chapter.name,
        value: chapter.resourceId,
        sortOrder: chapter.childFiles.length > 0
          ? chapter.childFiles[chapter.childFiles.length - 1].sortOrder
          : 0,
        hasChildren: chapter.childFiles.some((child: any) => child.isFolder), // 检查是否有子文件夹
      }));

    levels.value[level] = options;
    levels.value = levels.value.slice(0, level + 1); // 清除当前层级以下数据
    selections.value = selections.value.slice(0, level); // 清除当前层级以下选择
  }
  catch (error) {
    console.error('获取章节数据失败', error);
    message.error('获取章节数据失败');
  }
};

// 监听 isVisible 的变化
watch(
  () => props.isVisible,
  (newVal) => {
    if (newVal) {
      fetchChildren(props.courseFileId, 0); // 加载第一级数据
    }
    else {
      levels.value = []; // 重置层级数据
      selections.value = []; // 重置选择数据
    }
  },
);

// 处理选择变化
const handleSelectionChange = (value: string, level: number) => {
  selections.value[level] = value;
  const selectedOption = levels.value[level].find((item: any) => item.value === value);

  if (selectedOption?.hasChildren)
    fetchChildren(value, level + 1); // 加载下一层数据
};

// 确认移动
const handleOk = async () => {
  const lastSelection = selections.value[selections.value.length - 1];
  const selectedOption = levels.value.flat().find((item: any) => item.value === lastSelection);

  if (!selectedOption) {
    message.warning('请选择一个章节');
    return;
  }

  try {
    await handleSubchapterMove(
      props.sectionId,
      selectedOption.value,
      props.courseId,
      selectedOption.sortOrder,
    );
    message.success('移动成功');
    await props.fetchCourseData(props.resourceId, true, '');
  }
  catch (error) {
    console.error('请求失败', error);
    message.error('请求失败');
  }
  finally {
    props.onClose();
  }
};

// 取消移动
const handleCancel = () => {
  props.onClose();
};
</script>

<template>
  <a-modal
    title="移动到"
    :open="isVisible"
    ok-text="确定"
    cancel-text="取消"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <div v-for="(levelOptions, level) in levels" :key="level" style="margin-bottom: 16px;">
      <label>章节名称 (第 {{ level + 1 }} 层)</label>
      <a-select
        v-model:value="selections[level]"
        placeholder="请选择"
        style="width: 100%"
        @change="(value:any) => handleSelectionChange(value, level)"
      >
        <a-select-option
          v-for="option in levelOptions"
          :key="option.value"
          :value="option.value"
        >
          {{ option.label }}
        </a-select-option>
      </a-select>
    </div>
  </a-modal>
</template>
